////this is a Jquery plugin function that fire an event when the size of an element changed
//usage $().sizeChanged(function(){})
(function ($) {
    $.fn.sizeChanged = function (handleFunction) {
    var element = this;
    var lastWidth = element.width();
    var lastHeight = element.height();

    setInterval(function () {
        if (lastWidth === element.width()&&lastHeight === element.height())
            return;
        if (typeof (handleFunction) == 'function') {
            handleFunction({ width: lastWidth, height: lastHeight },
                           { width: element.width(), height: element.height() });
            lastWidth = element.width();
            lastHeight = element.height();
        }
    }, 100);
    return element;
    };

}(jQuery));

/** 将页脚固定在页面底部 */
function footerPosition(last, cur) {
    $("footer").removeClass("fixed-bottom");
    var contentHeight = document.body.scrollHeight;//网页正文全文高度
    var winHeight = window.innerHeight;//可视窗口高度，不包括浏览器顶部工具栏
    if(contentHeight <= winHeight){
        //当网页正文高度小于可视窗口高度时，为footer添加类fixed-bottom
        $("footer").addClass("fixed-bottom");
    }
}

$(function($){
    $("footer").css({"background-color": "#FFFFFF", "height": "60px"});
    $(document.body).css({"background": "#F3F3F3"});
    footerPosition();
    $(".admin-main").sizeChanged(footerPosition);
    // 页眉
    $("#div_header").html("<strong>JeeJio</strong>&nbsp;<small>OSAndroid&nbsp;技术沙龙</small>");
    // 页脚
    $("#footer_p").html('&copy;&nbsp;2020&nbsp;JeeJio.&nbsp;All&nbsp;rights&nbsp;reserved.&nbsp;'
        + '<small><a href="https://gitee.com/dybai/train" target="_blank">源代码</a></small>');
});

function getParameters(url) {
    var map = {};
    if (typeof url !== 'string') {
        url = url.toString();
    }
    var params = url.split("?");
    if (params.length < 2) {
        return map;
    }
    var list = params[1].split("&");
    for (var i = 0; i < list.length; i++) {
        var temp = list[i].split("=");
        map[temp[0]] = temp[1];
    }
    return map;
}

// 根据登录状态创建菜单
function create_login_menu() {
    var isLogin = false;
    $.ajax({
        url: '/lecturer/is_login',
        type: 'GET',
        contentType: "application/json",
        dataType: 'json',
        timeout: 30000,
        cache: false,
        async: false, // 同步执行，为了后面可以获取到 isLogin。
        success: function(data) {
            try {
                if (data.is_login) {
                    isLogin = true;

                    $("#a_login").attr("href", "#");
                    $("#a_login").text("退出登录");
                    $("#a_login").bind("click", menu_logout_click);

                    $("#hidn_login_name").val(data.login_name);
                    $("#hidn_full_name").val(data.full_name);

                    $("#full-name-text").text(data.full_name);
                    $("#full-name-text").parents("li").show();
                }
            } catch (err) {
                alert(err);
            }
        },
        error: function(request, status) {
            div_msg.css("color", "#FF0000");
            div_msg.html("服务器异常：" + status);
        }
    });
    return isLogin;
}

function index_onload() {
    var url = window.location.href;
    var small = $("#div_page_title small");

    var isLogin = create_login_menu();

    // 创建日历表格
    var date1 = new Date();
    var date2 = null;
    var showCount = 30;
    var count = 0;
    small.html("未来排期（" + showCount + "天）");
    var tbody = $("#tabDate tbody");
    var day = date1.getDay();
    var isFirstLine = true;
    while (count < showCount) {
        var tr = $("<tr class=\"am-text-center\"></tr>");
        for (var i = 0; i < 7; i++) {
            var td = $("<td></td>");
            if ((isFirstLine && (i < day)) || (count >= showCount)) {
                td.html("&nbsp;");
            } else {
                var month = (date1.getMonth() + 1);
                if (month < 10) month = "0" + month;
                var date = date1.getDate();
                var dateText = (date < 10) ? "0" + date : date;
                td.attr("date", date1.getFullYear() + "-" + month + "-" + dateText);
                td.text(date);
                date2 = new Date(date1);
                date2.setDate(date + 1);
                date1 = date2;
                count++;
            }
            $(tr).append(td);

            if (isLogin && td.attr("date")) {
                td.hover(calendar_hover_over, calendar_hover_out);
                td.bind("click", calendar_click);
            }
        }
        tbody.append(tr);
        isFirstLine = false;
    }

    // 标记有讲座的日期
    date2 = date1;
    date1 = new Date();
    var between = date1.getFullYear() + "-" + (date1.getMonth() + 1) + "-" + date1.getDate();
    var and = date2.getFullYear() + "-" + (date2.getMonth() + 1) + "-" + date2.getDate();
    mark_has_course_date(between, and, isLogin);

    if (isLogin) {
        $("#btn_create").show();
        $("#btn_create").bind("click", create_course);
    }
}

function findHasCourseDates(between, and, callback) {
    $.ajax({
        url: '/course/findHasCourseDates',
        type: 'GET',
        contentType: "application/json",
        data: {
            "between": between,
            "and": and
        },
        dataType: 'json',
        timeout: 30000,
        cache: false,
        success: function(data) {
            try {
                if (0 != data.state) {
                    if (console) console.log("Failed request /course/findHasCourseDates: " + data.msg);
                    return ;
                }
                callback(data.dates);
            } catch (err) {
                if (console) console.error(err);
            }
        },
        error: function(request, status) {
            if (console) console.error(err);
        }
    });
}

// 高亮有讲座的日期
function mark_has_course_date(between, and, isLogin) {
    findHasCourseDates(between, and, function(dates) {
        $("#tabDate tbody td").each(function(i) {
            var td = $(this);
            var curDate = td.attr("date");
            $(dates).each(function(i) {
                if (curDate && (curDate == this)) {
                    td.css("background-color", "#FFDFEF");
                    if (!isLogin) {
                        td.hover(calendar_hover_over, calendar_hover_out);
                        td.bind("click", calendar_click);
                    }
                    return false; // 避免同一个日期被绑定多次事件
                }
            });
        });
    });
}

function menu_logout_click() {
    $.ajax({
        url: '/lecturer/logout',
        type: 'GET',
        contentType: "application/json",
        dataType: 'json',
        timeout: 30000,
        cache: false,
        success: function(data) {
            try {
                window.location = "index.html";
            } catch (err) {
                alert(err);
            }
        },
        error: function(request, status) {
            div_msg.css("color", "#FF0000");
            div_msg.html("服务器异常：" + status);
        }
    });
}

function calendar_hover_over() {
    if (($("#divCourse").css("display") == "none") || ($("#hidn_course_day").val() != $(this).html())) {
        $(this).attr("out-bg-color", $(this).css("background-color"));
        $(this).css("background-color", "#C1FFC1");
    }
}

function calendar_hover_out() {
    if (($("#divCourse").css("display") == "none") || ($("#hidn_course_day").val() != $(this).html())) {
        $(this).css("background-color", $(this).attr("out-bg-color"));
    }
}

function calendar_click() {
    var currentDate = $(this).html();
    var lastDate = $("#hidn_course_day").val();
    if (currentDate == lastDate) { // 隐藏讲座列表
        $(this).css("background-color", $(this).attr("out-bg-color"));
        $("#divCourse").hide("fast");
        $("#hidn_course_day").val("");
        $("#hidn_course_date").val("");
    } else {
        if ($("#divCourse").css("display") == "none") { // 显示讲座列表
            $(this).css("background-color", "#C1FFC1");
            $("#divCourse").show("fast");
        } else { // 将讲座列表更新为当前点击日期的讲座
            $("#tabDate td").each(function() {
                if ($(this).html() == lastDate) {
                    $(this).css("background-color", $(this).attr("out-bg-color"));
                }
            });
            $(this).css("background-color", "#C1FFC1");
        }
        $("#hidn_course_day").val(currentDate);
        $("#hidn_course_date").val($(this).attr("date"));
        showCourseByDeliveryDate();
    }
}

// 显示选中的日期的讲座列表
function showCourseByDeliveryDate() {
    if ("" == $("#hidn_course_date").val()) {
        return ;
    }

    $("#btn_create").attr("disabled", "disabled");
    $("#btn_create").removeClass("am-btn-primary");
    $("#btn_create").addClass("am-disabled");

    var div_msg_panel = $("#div_msg_panel");
    var div_msg = $("#div_msg");

    $("#tabCourse tbody").empty();

    div_msg_panel.show("fast");
    div_msg.css("color", "#31761e");
    div_msg.html("查询中，请稍候...");
    $.ajax({
        url: '/course/findByDeliveryDate',
        type: 'GET',
        contentType: "application/json",
        data: {
            "date": $("#hidn_course_date").val(),
            "draft": 0
        },
        dataType: 'json',
        timeout: 30000,
        cache: false,
        success: function(data) {
            try {
                if (0 != data.state) {
                    div_msg.css("color", "#FF0000");
                    div_msg.html("查询失败：" + data.msg);
                } else {
                    setTimeout(function () { div_msg_panel.hide("fast"); }, 1000);
                    var courses = data.courses;
                    for (var i = 0; i < courses.length; i++) {
                        var tr = $('<tr class="am-text-center"></tr>');
                        var tdTime = $('<td><span>' + courses[i]["delivery_time"] + '</span>'
                            + '<input type="text" name="txt_delivery_time" value="' + courses[i]["delivery_time"] + '" style="display: none;" />'
                            + '<input type="hidden" name="hidn_course_id" value="' + courses[i]["id"] + '" /></td>');
                        var tdLecturer = $('<td>' + courses[i]["lecturer_full_name"] + '</td>');
                        var tdTitle = $('<td><span>' + courses[i]["title"] + '</span>'
                            + '<textarea rows="1" cols="20" style="display: none">' + courses[i]["title"] + '</textarea></td>');
                        var tdAddress = $('<td><span>' + courses[i]["address"] + '</span>'
                            +'<input type="text" value="' + courses[i]["address"] + '" style="display: none" /></td>');
                        var tdEdit = $('<td></td>');
                        if (courses[i]["allow_edit"]) {
                            var a_modify = $('<a href="#" name="a_modify">修改</a>');
                            a_modify.bind("click", courses[i]["id"], edit_course);
                            tdEdit.append(a_modify);
                            var a_release = $('<a href="#" name="a_release" style="display: none">立即发布</a>');
                            a_release.bind("click", courses[i]["id"], release_course);
                            tdEdit.append(a_release);
                            if (courses[i]["allow_draft"]) {
                                tdEdit.append('<br/>');
                                var a_draft = $('<a href="#" name="a_draft" style="display: none">存为草稿</a>');
                                //a_draft.bind("click", draft_new_course); // XXX
                                tdEdit.append(a_draft);
                            }
                            tdEdit.append('<br/>');
                            var a_cancel = $('<a href="#" name="a_cancel" style="display: none">放弃编辑</a>');
                            a_cancel.bind("click", courses[i]["id"], cancel_edit_course);
                            tdEdit.append(a_cancel);
                        }
                        var enclosureText = "下载附件";
                        if (courses[i]["allow_edit"]) {
                            enclosureText = "管理附件";
                        }
                        var tdEnclosure = $('<td><a href="attach.html?course_id=' + courses[i]["id"]
                            + '&allow_edit=' + courses[i]["allow_edit"]
                            + '&course_title=' + encodeURI(courses[i]["title"])
                            + '" target="_blank">' + enclosureText + '</a></td>');
                        var tdDelete = $('<td></td>');
                        if (courses[i]["allow_edit"]) {
                            var a_delete = $('<a href="#">删除</a>');
                            a_delete.bind("click", courses[i]["id"], delete_course);
                            tdDelete.append(a_delete);
                        }
                        tr.append(tdTime).append(tdLecturer).append(tdTitle).append(tdAddress).append(tdEdit).append(tdEnclosure).append(tdDelete);
                        $("#tabCourse tbody").append(tr);
                    }
                }
            } catch (err) {
                alert(err);
            }
            $("#btn_create").removeAttr("disabled", "disabled");
            $("#btn_create").removeClass("am-disabled");
            $("#btn_create").addClass("am-btn-primary");
        },
        error: function(request, status, errorThrown) {
            div_msg.css("color", "#FF0000");
            div_msg.html("服务器异常：" + request.status);
        }
    });
}

// 创建讲座按钮单击事件
function create_course() {
    $("#btn_create").attr("disabled", "disabled");
    $("#btn_create").removeClass("am-btn-primary");
    $("#btn_create").addClass("am-disabled");

    var tr = $('<tr class="am-text-center"></tr>');
    var tdTime = $('<td><input type="text" id="txt_delivery_time"/></td>');
    var tdLecturer = $('<td>' + $("#hidn_full_name").val() + '</td>');
    var tdTitle = $('<td><textarea id="txt_title" rows="1" cols="20"></textarea></td>');
    var tdAddress = $('<td><input type="text" id="txt_address"/></td>');
    var tdEdit = $('<td><a href="#" id="a_release">立即发布</a><br/><a href="#" id="a_draft" style="display: none">存为草稿</a></td>');
    tdEdit.find("#a_release").bind("click", release_new_course);
    tdEdit.find("#a_draft").bind("click", draft_new_course);
    var tdEnclosure = $('<td>&nbsp;</td>');
    var tdDelete = $('<td><a href="#">放弃</a></td>');
    tdDelete.bind("click", true, delete_new_course);
    tr.append(tdTime).append(tdLecturer).append(tdTitle).append(tdAddress).append(tdEdit).append(tdEnclosure).append(tdDelete);
    $("#tabCourse tbody").append(tr);

    //时间选择器
    laydate.render({
      elem: '#txt_delivery_time'
      ,type: 'time'
    });
}

// 发布讲座
function release_new_course() {
    var txt_delivery_time = $("#txt_delivery_time");
    var txt_title = $("#txt_title");
    var txt_address = $("#txt_address");
    var div_msg_panel = $("#div_msg_panel");
    var div_msg = $("#div_msg");

    div_msg_panel.show("fast");
    div_msg.css("color", "#FF0000");
    if (txt_delivery_time.val() == "") {
        div_msg.html("请选择讲座开始时间");
        delivery_time.focus();
        return ;
    }
    if (txt_title.val().trim() == "") {
         div_msg.html("请输入讲座主题");
        $("#txt_title").focus();
        return ;
    }
    div_msg.css("color", "#31761e");
    div_msg.html("正在提交，请稍候...");
    $.ajax({
        url: '/course/create',
        type: 'GET',
        contentType: "application/json",
        data: {
            "datetime": $("#hidn_course_date").val() + " " + txt_delivery_time.val(),
            "title": txt_title.val().trim(),
            "address": txt_address.val().trim(),
            "draft": 0
        },
        dataType: 'json',
        timeout: 30000,
        cache: false,
        success: function(data) {
            try {
                if (0 != data.state) {
                    div_msg.css("color", "#FF0000");
                    div_msg.html("提交失败：" + data.msg);
                } else {
                    div_msg.css("color", "#31761e");
                    div_msg.html("提交成功");
                    delete_new_course(false);
                    setTimeout(function () { showCourseByDeliveryDate(); }, 1000);
                }
            } catch (err) {
                alert(err);
            }
        },
        error: function(request, status, errorThrown) {
            div_msg.css("color", "#FF0000");
            div_msg.html("服务器异常：" + errorThrown);
        }
    });
}

// 将讲座保存为草稿
function draft_new_course() {
}

// 开始编辑讲座
function edit_course(course_id) {
    $("#tabCourse tbody tr").each(function() {
        if ($(this).find("input[name='hidn_course_id']").val() == course_id.data) {
            $(this).children("td").each(function(i) {
                switch (i) {
                    case 0: { // 时间
                        $(this).children('span').hide();
                        $(this).children('input[name="txt_delivery_time"]').show();
                        var txt_delivery_time = $(this).children('input[name="txt_delivery_time"]').get(0);
                        //时间选择器
                        laydate.render({
                          elem: txt_delivery_time,
                          type: 'time'
                        });
                        break;
                    }
                    case 2: { // 主题
                        $(this).children('span').hide();
                        $(this).children('textarea').show();
                        break;
                    }
                    case 3: { // 地点
                        $(this).children('span').hide();
                        $(this).children('input').show();
                        break;
                    }
                    case 4: { // 编辑
                        $(this).children('a[name="a_modify"]').hide();
                        $(this).children('a[name="a_release"]').show();
                        $(this).children('a[name="a_draft"]').show();
                        $(this).children('a[name="a_cancel"]').show();
                        break;
                    }
                    case 6: { // 删除
                        break;
                    }
                }
            });
            return false;
        }
    });
}

function disable_edit_course(course_id, is_sync) {
    $("#tabCourse tbody tr").each(function() {
        if ($(this).find("input[name='hidn_course_id']").val() == course_id) {
            $(this).children("td").each(function(i) {
                switch (i) {
                    case 0: { // 时间
                        if (is_sync) {
                            $(this).children('span').html($(this).children('input[name="txt_delivery_time"]').val());
                        }
                        $(this).children('span').show();
                        $(this).children('input[name="txt_delivery_time"]').hide();
                        break;
                    }
                    case 2: { // 主题
                        if (is_sync) {
                            $(this).children('span').html($(this).children('textarea').val());
                        }
                        $(this).children('span').show();
                        $(this).children('textarea').hide();
                        break;
                    }
                    case 3: { // 地点
                        if (is_sync) {
                            $(this).children('span').html($(this).children('input').val());
                        }
                        $(this).children('span').show();
                        $(this).children('input').hide();
                        break;
                    }
                    case 4: { // 编辑
                        $(this).children('a[name="a_modify"]').show();
                        $(this).children('a[name="a_release"]').hide();
                        $(this).children('a[name="a_draft"]').hide();
                        $(this).children('a[name="a_cancel"]').hide();
                        break;
                    }
                    case 6: { // 删除
                        break;
                    }
                }
            });
            return false;
        }
    });
}

function cancel_edit_course(course_id) {
    if (!confirm("确认放弃编辑吗？")) {
        return ;
    }
    disable_edit_course(course_id.data, false);
}

// 保存修改讲座
function release_course(course_id) {
    var div_msg_panel = $("#div_msg_panel");
    var div_msg = $("#div_msg");

    div_msg_panel.show("fast");
    div_msg.css("color", "#FF0000");

    var delivery_time = "";
    var title = "";
    var address = "";
    $("#tabCourse tbody tr").each(function() {
        if ($(this).find("input[name='hidn_course_id']").val() == course_id.data) {
            var tds = $(this).children("td");
            delivery_time = $(tds[0]).children('input[name="txt_delivery_time"]').val(); // 时间
            if ("" == delivery_time) {
                div_msg.html("请选择讲座开始时间");
                delivery_time.focus();
                return ;
            }
            title = $(tds[2]).children('textarea').val(); // 主题
            if ("" == title) {
                 div_msg.html("请输入讲座主题");
                $("#txt_title").focus();
                return ;
            }
            address = $(tds[3]).children('input').val(); // 地点
            return false;
        }
    });

    div_msg.css("color", "#31761e");
    div_msg.html("正在提交，请稍候...");

    $.ajax({
        url: '/course/modify',
        type: 'GET',
        contentType: "application/json",
        data: {
            "id": course_id.data,
            "datetime": $("#hidn_course_date").val() + " " + delivery_time,
            "title": title,
            "address": address,
            "draft": 0
        },
        dataType: 'json',
        timeout: 30000,
        cache: false,
        success: function(data) {
            try {
                if (0 != data.state) {
                    div_msg.css("color", "#FF0000");
                    div_msg.html("提交失败：" + data.msg);
                } else {
                    div_msg.css("color", "#31761e");
                    div_msg.html("提交成功");
                    setTimeout(function () { div_msg_panel.hide("fast"); }, 5000);
                    disable_edit_course(course_id.data, true);
                }
            } catch (err) {
                alert(err);
            }
        },
        error: function(request, status, errorThrown) {
            div_msg.css("color", "#FF0000");
            div_msg.html("服务器异常：" + request.status);
        }
    });
}

// 删除讲座（删除新增行）
function delete_new_course(is_from_user) {
    if (is_from_user && (!confirm("确认放弃编辑本条目？"))) {
        return ;
    }
    $("#tabCourse tbody tr:last").remove();
    $("#btn_create").removeAttr("disabled");
    $("#btn_create").removeClass("am-disabled");
    $("#btn_create").addClass("am-btn-primary");
}

// 删除讲座
function delete_course(course_id) {
    if (!confirm("确认删除此讲座吗？")) {
        return ;
    }
    var div_msg_panel = $("#div_msg_panel");
    var div_msg = $("#div_msg");

    div_msg_panel.show("fast");
    $.ajax({
        url: '/course/delete',
        type: 'GET',
        contentType: "application/json",
        data: {
            "id": course_id.data
        },
        dataType: 'json',
        timeout: 30000,
        cache: false,
        success: function(data) {
            try {
                if (0 != data.state) {
                    div_msg.css("color", "#FF0000");
                    div_msg.html("删除失败：" + data.msg);
                } else {
                    div_msg.css("color", "#31761e");
                    div_msg.html("删除成功");
                    setTimeout(function () { div_msg_panel.hide("fast"); }, 5000);
                    $('#tabCourse tbody tr input[name="hidn_course_id"][value="' + course_id.data + '"]').parents("tr").remove();
                }
            } catch (err) {
                alert(err);
            }
        },
        error: function(request, status, errorThrown) {
            div_msg.css("color", "#FF0000");
            div_msg.html("服务器异常：" + request.status);
        }
    });
}

function login_onload() {
    $("#btn_submit").bind("click", login_submit);
}

function login_submit() {
    var txtName = $("#txtName");
    var txtPwd = $("#txtPwd");
    var div_msg_panel = $("#div_msg_panel");
    var div_msg = $("#div_msg");

    div_msg_panel.show("fast");
    div_msg.css("color", "#FF0000");
    if ("" == txtName.val()) {
        div_msg.html("请填写用户名");
        txtName.focus();
        return ;
    } else if ("" == txtPwd.val()) {
        div_msg.html("请填写密码");
        txtPwd.focus();
        return ;
    }
    div_msg.css("color", "#31761e");
    div_msg.html("正在登录，请稍候...");
    $.ajax({
        url: '/lecturer/login',
        type: 'GET',
        contentType: "application/json",
        data: {
            "name": txtName.val(),
            "pwd": txtPwd.val()
        },
        dataType: 'json',
        timeout: 30000,
        cache: false,
        success: function(data) {
            try {
                if (0 != data.state) {
                    div_msg.css("color", "#FF0000");
                    div_msg.html("登录失败：" + data.msg);
                } else {
                    div_msg.css("color", "#31761e");
                    div_msg.html("登录成功");
                    fm.reset();
                    window.location = "index.html";
                }
            } catch (err) {
                alert(err);
            }
        },
        error: function(request, status) {
            div_msg.css("color", "#FF0000");
            div_msg.html("服务器异常：" + status);
        }
    });
}

function history_onload() {
    var div_msg_panel = $("#div_msg_panel");
    var div_msg = $("#div_msg");

    create_login_menu();

    $("#tabCourse tbody").empty();

    div_msg_panel.show("fast");
    div_msg.css("color", "#31761e");
    div_msg.html("查询中，请稍候...");
    $.ajax({
        url: '/course/findHistory',
        type: 'GET',
        contentType: "application/json",
        dataType: 'json',
        timeout: 30000,
        cache: false,
        success: function(data) {
            try {
                if (0 != data.state) {
                    div_msg.css("color", "#FF0000");
                    div_msg.html("查询失败：" + data.msg);
                } else {
                    setTimeout(function () { div_msg_panel.hide("fast"); }, 1000);
                    var courses = data.courses;
                    for (var i = 0; i < courses.length; i++) {
                        var tr = $('<tr class="am-text-center"></tr>');
                        var tdTime = $('<td><span>' + courses[i]["delivery_time"] + '</span>'
                            + '<input type="text" name="txt_delivery_time" value="' + courses[i]["delivery_time"] + '" style="display: none;" />'
                            + '<input type="hidden" name="hidn_course_id" value="' + courses[i]["course_id"] + '" /></td>');
                        var tdLecturer = $('<td>' + courses[i]["lecturer_full_name"] + '</td>');
                        var tdTitle = $('<td><span>' + courses[i]["title"] + '</span></td>');
                        var tdAddress = $('<td><span>' + courses[i]["address"] + '</span></td>');
                        var enclosureText = "下载附件";
                        if (courses[i]["allow_edit"]) {
                            enclosureText = "管理附件";
                        }
                        var tdEnclosure = $('<td><a href="attach.html?course_id=' + courses[i]["course_id"]
                             + '&allow_edit=' + courses[i]["allow_edit"]
                             + '&course_title=' + encodeURI(courses[i]["title"])
                             + '" target="_blank">' + enclosureText + '</a></td>');
                        tr.append(tdTime).append(tdLecturer).append(tdTitle).append(tdAddress).append(tdEnclosure);
                        $("#tabCourse tbody").append(tr);
                    }
                }
            } catch (err) {
                alert(err);
            }
        },
        error: function(request, status, errorThrown) {
            div_msg.css("color", "#FF0000");
            div_msg.html("服务器异常：" + request.status);
        }
    });
}

function find_attach_by_course(course_id) {
    var div_msg_panel = $("#div_msg_panel");
    var div_msg = $("#div_msg");

    div_msg_panel.show("fast");
    div_msg.css("color", "#31761e");
    div_msg.html("查询中，请稍候...");

    $("#tabAttach tbody").empty();

    $.ajax({
        url: '/attach/findByCourse?courseId=' + course_id,
        type: 'GET',
        contentType: "application/json",
        dataType: 'json',
        timeout: 30000,
        cache: false,
        success: function(data) {
            try {
                if (0 != data.state) {
                    div_msg.css("color", "#FF0000");
                    div_msg.html("查询失败：" + data.msg);
                } else {
                    setTimeout(function () { div_msg_panel.hide("fast"); }, 1000);
                    var attach_list = data.attach_list;
                    for (var i = 0; i < attach_list.length; i++) {
                        var tr = $('<tr class="am-text-center"></tr>');
                        var tdDisplayName = $('<td>' + attach_list[i]["display_name"] + '</td>');
                        var tdCreateTime = $('<td><span>' + attach_list[i]["create_time"] + '</span></td>');
                        var tdDownload = $('<td><span><a href="/attach/downloadById?id='
                            + attach_list[i]["attach_id"] + '">下载</a></span></td>');
                        var tdDelete = $('<td>&nbsp;</td>');
                        if (data.allow_edit) {
                            var aDelete = $('<a href="#">删除</a>');
                            aDelete.bind("click", attach_list[i]["attach_id"], attach_delete);
                            tdDelete = $('<td></td>');
                            tdDelete.append(aDelete);
                        }
                        tr.append(tdDisplayName).append(tdCreateTime).append(tdDownload).append(tdDelete);
                        $("#tabAttach tbody").append(tr);
                    }
                }
            } catch (err) {
                div_msg.css("color", "#FF0000");
                div_msg.html("服务器返回的数据无效：" + err);
            }
        },
        error: function(request, status, errorThrown) {
            div_msg.css("color", "#FF0000");
            div_msg.html("服务器异常：" + request.status);
        }
    });
}

function attach_onload() {
    var parameters = getParameters(window.location);
    $("#hidn_course_id").val(parameters.course_id);
    if ("true" == parameters.allow_edit) {
        $("#div_upload").removeClass("am-hide");
    }
    if (parameters.course_title) {
        var title = decodeURI(parameters.course_title);
        var sharpIndex = title.indexOf("#");
        if (sharpIndex >= 0) {
            title = title.substring(0, sharpIndex);
        }
        $("#sp_course_title").html(title);
    }

    find_attach_by_course(parameters.course_id);

    $("#btn_upload").bind("click", attach_upload);
}

function attach_upload() {
    var fileAttach = $("#file_attach");
    var txtDisplay = $("#txt_display");
    var filePath = $("#file_attach").val();
    var pbg = $("#div_pb_bg_upload");
    var pfg = $("#div_pb_fg_upload");

    $("#pre_upload").parent().parent().addClass("am-hide");
    $("#pre_upload").html("");

    if ($.trim(filePath) == "") {
        $("#pre_upload").parent().parent().removeClass("am-hide");
        $("#pre_upload").html("请选择需要上传的文件！");
        return ;
    }
    if ($.trim(txtDisplay.val()) == "") {
        var fileName = filePath.substring(filePath.lastIndexOf("\\") + 1);
        txtDisplay.val(fileName);
    }
    if ($("#file_attach").get(0).files[0].size > 20971520) {
        $("#pre_upload").parent().parent().removeClass("am-hide");
        $("#pre_upload").html("文件超过上传限制（20971520 Bytes）。");
        return ;
    }

    pbg.removeClass("am-hide");

    var formData = new FormData();
    formData.append("courseId", $("#hidn_course_id").val());
    formData.append("displayName", txtDisplay.val());
    formData.append("file", $("#file_attach").get(0).files[0]);

    $.ajax({
        url: '/attach/upload',
        type: 'POST',
        contentType: false,
        data: formData,
        processData: false,
        dataType: 'json',
        timeout: 30000,
        cache: false,
        xhr: function() {
            var xhr = new XMLHttpRequest();
            xhr.upload.addEventListener('progress', function(e) {
                var percent = Math.round((e.loaded / e.total) * 100) + '%';
                pfg.css("width", percent);
                pfg.html(percent);
            });
            return xhr;
        },
        success: function(data) {
            pbg.addClass("am-hide");
            try {
                $("#pre_upload").parent().parent().removeClass("am-hide");
                $("#pre_upload").html(data.msg);
                if (0 == data.state) { // 上传成功
                    $("#file_attach").get(0).outerHTML = $("#file_attach").get(0).outerHTML;
                    txtDisplay.val("");
                    find_attach_by_course($("#hidn_course_id").val());
                }
            } catch (err) {
                $("#pre_upload").parent().parent().removeClass("am-hide");
                $("#pre_upload").html("服务器返回的数据无效：" + err);
            }
        },
        error: function(request, status, errorThrown) {
            pbg.addClass("am-hide");
            $("#pre_upload").parent().parent().removeClass("am-hide");
            $("#pre_upload").html("服务器异常：(" + request.status + ")" + request.statusText);
        }
    });
}

function attach_delete(event) {
    var div_msg_panel = $("#div_msg_panel");
    var div_msg = $("#div_msg");

    if (!confirm("确认删除此文件吗？")) return;

    div_msg_panel.show("fast");
    div_msg.css("color", "#31761e");
    div_msg.html("删除中，请稍候...");

    var attach_id = event.data;

    $.ajax({
        url: '/attach/deleteById?id=' + attach_id,
        type: 'GET',
        contentType: "application/json",
        dataType: 'json',
        timeout: 30000,
        cache: false,
        success: function(data) {
            try {
                if (0 != data.state) {
                    div_msg.css("color", "#FF0000");
                    div_msg.html("删除失败：" + data.msg);
                } else {
                    setTimeout(function () { div_msg_panel.hide("fast"); }, 1000);
                    $(event.target).parent().parent().remove(); // 删除当前行
                    div_msg.css("color", "#31761e");
                    div_msg.html("删除成功");
                }
            } catch (err) {
                div_msg.css("color", "#FF0000");
                div_msg.html("服务器返回的数据无效：" + err);
            }
        },
        error: function(request, status, errorThrown) {
            div_msg.css("color", "#FF0000");
            div_msg.html("服务器异常：" + request.status);
        }
    });
}
